package com.ict.web.task;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ict.common.core.domain.entity.SysDept;
import com.ict.common.utils.StringUtils;
import com.ict.common.utils.uuid.IdUtils;
import com.ict.system.service.ISysDeptService;
import com.ict.web.rabbitMqConfig.DeptDomain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 异步工厂（产生任务用）
 * @author xc
 */
public class RefreshDeptTaskAsyncFactory {

    private static final Logger logger =
            LoggerFactory.getLogger(RefreshDeptTaskAsyncFactory.class);

    //部门数据对接接口
    public static final String DEPT_URL="http://100.100.104.12:21100/rest";
    private static final String APP_CODE="smartcity_user_sync";
    private static final String DEPT_API_CODE="API_CODE_1630029712265597200";
    public static JSONArray  tableData = new JSONArray ();
    public static JSONObject itemObj = new JSONObject();



    /**
     * 同步部门信息数据
     *
     * @return 任务task
     */
    public static TimerTask asyncStatus(final ISysDeptService deptService) {

        return new TimerTask() {
            @Override
            @Transactional(rollbackFor = Exception.class)
            public void run() {
                logger.error("------同步部门数据--------");
                JSONObject jsonDept = new JSONObject();
                jsonDept.put("departIds", null);
                HashMap<String, String> headersDept = new HashMap<>();
                headersDept.put("appCode", APP_CODE);
                headersDept.put("apiCode", DEPT_API_CODE);
                headersDept.put("apiVersion", "1.0.0");
                headersDept.put("format", "restful");
                headersDept.put("Content-Type", "application/json");
                String depetList = HttpUtil.createGet(DEPT_URL).addHeaders(headersDept).form(jsonDept).execute().body();
                JSONObject obj= JSONObject.parseObject(depetList);
                String json = obj.getJSONObject("result").getJSONArray("result").toString();
                JSONArray jsonArray = JSONArray.parseArray(json);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    itemObj = JSONObject.parseObject(itemObj.toJSONString());
                    itemObj.put("id",jsonObject.getString("id"));
                    itemObj.put("departName",jsonObject.getString("departName"));
                    itemObj.put("departOrder",jsonObject.getString("departOrder"));
                    itemObj.put("parentId",jsonObject.getString("parentId"));
                    itemObj.put("departNameAbbr",jsonObject.getString("departNameAbbr"));
                    itemObj.put("orgCategory",jsonObject.getString("orgCategory"));
                    itemObj.put("title",jsonObject.getString("title"));
                    itemObj.put("orgType",jsonObject.getString("orgType"));
                    itemObj.put("orgCode",jsonObject.getString("orgCode"));
                    itemObj.put("delFlag",jsonObject.getString("delFlag"));
                    itemObj.put("updateTime",jsonObject.getString("updateTime"));
                    itemObj.put("createTime",jsonObject.getString("createTime"));
                    tableData.add(itemObj);
                    JSONArray children = jsonArray.getJSONObject(i).getJSONArray("children");
                    getChildren(children);
                }
                System.out.print(tableData);
                List<DeptDomain> deptDomains = tableData.toJavaList(DeptDomain.class);
                tableData=new JSONArray();
                List<SysDept> sysDeptList = deptService.selectLastDept();
                List<DeptDomain> collect = deptDomains.stream().filter(
                        s->sysDeptList.stream()
                                .map(SysDept::getFormerId)
                                .noneMatch(a-> Objects.deepEquals(s.getId(),a)))
                        .collect(Collectors.toList());
                List<SysDept> list = new ArrayList<>();
                collect.stream().forEach(s->{
                    SysDept dept = new SysDept();
                    dept.setDeptId(IdUtils.snowId());
                    dept.setDeptName(s.getDepartName());
                    dept.setOrderNum(s.getDepartOrder());
                    dept.setStatus("0");
                    dept.setDelFlag("0");
                    dept.setOrgCategory(s.getOrgCategory());
                    dept.setFormerId(s.getId());
                    dept.setFormerParentId(s.getParentId());
                    SysDept parentDept = deptService.selectDept(s.getParentId());
                    if(StringUtils.isNotNull(parentDept)){
                        dept.setParentId(parentDept.getDeptId());
                        String ancestors = parentDept.getAncestors();
                        dept.setAncestors(ancestors+","+parentDept.getDeptId());
                    }
                    deptService.insertDept(dept);
                    list.add(dept);
                });
                logger.info("同步部门数据:已同步完成");
            }


            public  void getChildren(JSONArray children){
                for (int i = 0; i < children.size(); i++) {
                    JSONObject jsonObject = children.getJSONObject(i);
                    JSONArray children1 = jsonObject.getJSONArray("children");
                    itemObj = JSONObject.parseObject(itemObj.toJSONString());
                    itemObj.put("id",jsonObject.getString("id"));
                    itemObj.put("departName",jsonObject.getString("departName"));
                    itemObj.put("departOrder",jsonObject.getString("departOrder"));
                    itemObj.put("parentId",jsonObject.getString("parentId"));
                    itemObj.put("departNameAbbr",jsonObject.getString("departNameAbbr"));
                    itemObj.put("orgCategory",jsonObject.getString("orgCategory"));
                    itemObj.put("title",jsonObject.getString("title"));
                    itemObj.put("orgType",jsonObject.getString("orgType"));
                    itemObj.put("orgCode",jsonObject.getString("orgCode"));
                    itemObj.put("delFlag",jsonObject.getString("delFlag"));
                    itemObj.put("updateTime",jsonObject.getString("updateTime"));
                    itemObj.put("createTime",jsonObject.getString("createTime"));
                    if(children1 != null && children1.size() > 0){
                        //有子节点，递归
                        tableData.add(itemObj);
                        getChildren(children1);
                    }else{//无子节点
                        tableData.add(itemObj);
                        continue;
                    }
                    itemObj = new JSONObject();
                }
            }

        };
    }
}
